import { useState, useEffect, useRef, useContext } from 'react'
import { Table, Form, Input, Button, Modal, message } from 'antd'
import { configContext, getLocalValue } from '../../config/env'
import commonService from '../../service/index'

function NodeManage() {
  const [tableData, setData] = useState([])
  const [loading, setLoading] = useState(true)
  const [param, setParam] = useState({
    id: ''
  })
  const [createModal, setCreateModal] =  useState(false)
  const [onLineModal, setModal] = useState(false)
  const [modalValue, setModalValue] = useState(false)
  const [formModal, setFormModal] = useState(false)
  const [height, setHeight] = useState(600)
  const tableRef = useRef<any>()
  const localValue = useContext(configContext)
  const [form] = Form.useForm()
  const [formRef] = Form.useForm()
  const [formObj] = Form.useForm()
  const [formValue] = Form.useForm()
  const nodeIdRef = useRef('')

  useEffect(() => {
    getData()
    if (tableRef.current && tableRef.current.offsetHeight) {
      setHeight(tableRef.current.offsetHeight)
    }
  }, [])

  const getData = async () => {
    setData([])
    setLoading(true)
    const data:any = await commonService.getNodeData({
      and: '(node_type.eq.NODE_TYPE_VOD_CAPTRANS)'
    })
    setLoading(false)
    if (data) {
      setData(param.id ? data.filter((item: any) => item.node_id == param.id) : data)
    }
  }
  
  const getParamValue = (e:any, type:string) => {
    setParam({
      ...param,
      [type]: e.target.value
    })
  }

  const handleCreateResource = async () => { // 注入一个点播资源
    const value = form.getFieldsValue()
    const data:any = await commonService.createNodeResource({
      capture_node_id: value.capture_node_id || '',
      stream_title: value.stream_title || '',
      stream_id: value.stream_id || '',
      cache_node_id_assign: value.cache_node_id_assign || '',
      media_url: value.media_url || ''
    })
    if (!data.message) {
      message.success('注入资源成功')
      setCreateModal(false)
      getData()
    } else {
      message.error(data.message)
    }
  }

  const handleOnLineResource = async () => { // 上线一个点播资源
    const value = formRef.getFieldsValue()
    const data:any = await commonService.onlineNodeResource({
      cache_node_id_assign: value.cache_node_id_assign || '',
      edge_node_id_assign: value.edge_node_id_assign || '',
      media_code: value.media_code || '',
      area_id: value.area_id || ''
    })
    if (!data.message) {
      message.success('上线点播资源成功')
      setModal(false)
      getData()
    } else {
      message.error(data.message)
    }
  }

  const handleOffLineResource = async () => { // 下线一个点播资源
    const value = formObj.getFieldsValue()
    const data:any = await commonService.offlineNodeResource({
      edge_node_id_assign: value.edge_node_id_assign || '',
      media_code: value.media_code || '',
      area_id: value.area_id || ''
    })
    if (!data.message) {
      message.success('下线点播资源成功')
      setModalValue(false)
      getData()
    } else {
      message.error(data.message)
    }
  }

  const handleClearResource = async () => { // 撤销一个点播资源
    const value = formObj.getFieldsValue()
    const data:any = await commonService.clearNodeResource({
      cache_node_id_assign: value.cache_node_id_assign || '',
      media_code: value.media_code || ''
    })
    if (!data.message) {
      message.success('撤销点播资源成功')
      setFormModal(false)
      getData()
    } else {
      message.error(data.message)
    }
  }


  return ( 
     <div className='table-content' ref={tableRef}>
       <div className='title'>{getLocalValue(localValue, '点播节点','point node')}</div>
       <div className='table'>
        <div className='form'>
        <Form layout='inline'>
          <Form.Item label={getLocalValue(localValue, '节点ID','node ID')}>
            <Input style={{width: 200}} value={param.id} allowClear onChange={(e) => getParamValue(e, 'id')} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" onClick={getData}>{getLocalValue(localValue, '查询','query')}</Button>
            <Button type="primary" style={{marginLeft: '10px'}} onClick={() => {setModal(true);formRef && formRef.resetFields()}}>{getLocalValue(localValue, '上线点播资源','online on demand resource')}</Button>
            <Button type="primary" style={{marginLeft: '10px'}} onClick={() => {setModalValue(true);formObj && formObj.resetFields()}}>{getLocalValue(localValue, '下线点播资源','offline on demand resource')}</Button>
            <Button type="primary" style={{marginLeft: '10px'}} onClick={() => {setFormModal(true);formValue && formValue.resetFields()}}>{getLocalValue(localValue, '撤销点播资源','clear on demand resource')}</Button>
          </Form.Item>
        </Form>
        </div>
        <Table loading={loading} dataSource={tableData} pagination={false} scroll={{y: height - 200}} rowKey='node_id' columns={
          [{
            title: getLocalValue(localValue, '节点ID','node ID'),
            dataIndex: 'node_id',
            width: 100
          },
          {
            title: getLocalValue(localValue, '节点IP','node IP'),
            dataIndex: 'node_ip',
            width: 139
          },
          {
            title: getLocalValue(localValue, '节点类型','node type'),
            dataIndex: 'node_type',
            width: 160,
          },
          {
            title: 'exchange_name',
            dataIndex: 'exchange_name'
          },
          {
            title: 'queue_name',
            dataIndex: 'queue_name'
          },
          {
            title: 'router_key',
            dataIndex: 'router_key'
          },
          {
            title: 'area_id',
            dataIndex: 'area_id',
            width: 100
          },
          {
            title: getLocalValue(localValue, '描述','description'),
            dataIndex: 'description'
          },
          {
            title: getLocalValue(localValue, '操作','action field'),
            width: 130,
            render: (row) => {
              return <Button type="link" size='small' onClick={() => { nodeIdRef.current = row.node_id; setCreateModal(true); form && form.resetFields(); form && form.setFieldsValue({ capture_node_id: row.node_id }); }}>{getLocalValue(localValue, '注入点播资源','injection resource')}</Button>
            }
          }]
        } ></Table>
       </div>

       <Modal title={getLocalValue(localValue, '注入点播资源', 'inject on demand resource')} width={600} open={createModal} maskClosable={false}	okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleCreateResource} onCancel={() => {setCreateModal(false) }} >
          <Form form={form} initialValues={{capture_node_id: nodeIdRef.current}} layout='inline' labelCol={{span: 6}}>
            <Form.Item label={getLocalValue(localValue, '节点ID', 'node id')} name='capture_node_id' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='stream_title' name='stream_title' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='stream_id' name='stream_id' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='cache_node_id_assign' name='cache_node_id_assign' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='media_url' name='media_url' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
          </Form>
       </Modal>

       <Modal title={getLocalValue(localValue, '上线点播资源', 'online on demand resource')} width={600} open={onLineModal} maskClosable={false}	okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleOnLineResource} onCancel={() => {setModal(false) }} >
          <Form form={formRef} layout='inline' labelCol={{span: 6}}>
            <Form.Item label='cache_node_id_assign' name='cache_node_id_assign' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='edge_node_id_assign' name='edge_node_id_assign' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='media_code' name='media_code' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='area_id' name='area_id' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
          </Form>
       </Modal>

       <Modal title={getLocalValue(localValue, '下线点播资源', 'offline on demand resource')} width={600} open={modalValue} maskClosable={false}	okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleOffLineResource} onCancel={() => {setModalValue(false) }} >
          <Form form={formObj} layout='inline' labelCol={{span: 6}}>
            <Form.Item label='edge_node_id_assign' name='edge_node_id_assign' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='media_code' name='media_code' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='area_id' name='area_id' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
          </Form>
       </Modal>

       <Modal title={getLocalValue(localValue, '撤销点播资源', 'clear on demand resource')} width={600} open={formModal} maskClosable={false}	okText={getLocalValue(localValue, '确定', 'OK')} cancelText={getLocalValue(localValue, '取消', 'cancel')} onOk={handleClearResource} onCancel={() => {setFormModal(false) }} >
          <Form form={formValue} layout='inline' labelCol={{span: 6}}>
            <Form.Item label='cache_node_id_assign' name='cache_node_id_assign' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
            <Form.Item label='media_code' name='media_code' style={{marginTop: '20px', width: '100%'}}>
              <Input style={{width: '100%'}} allowClear />
            </Form.Item>
          </Form>
       </Modal>

     </div>
  )
}


export default NodeManage